package com.cy.pj.goods.dao;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;

import javax.sql.DataSource;
import java.sql.*;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Repository
public class DefaultGoodsDao implements GoodsDao {

    Connection conn = null;
    Statement stat = null;
    ResultSet re = null;
    ResultSetMetaData resultSetMetaData = null;

    @Autowired
    private DataSource dataSource;


    @Override
    public List<Map<String, Object>> findGoods() throws SQLException {

        try {
            //获取数据库连接
            conn = dataSource.getConnection();

            //获取传输器
            stat = conn.createStatement();

            //执行SQL语句,生成结果集

            String sql = "select * from tb_goods";
            re = stat.executeQuery(sql);

            //遍历结果集,将结果存入List集合
            List<Map<String, Object>> list = new ArrayList<Map<String, Object>>();



            while (re.next()) {
//                Map map = new HashMap();
//
//                int id = re.getInt("id");
//                String name = re.getString("name");
//                String remark = re.getString("remark");
//                String createdTime = re.getString("createdTime");
//
//                map.put("id", id);
//                map.put("name", name);
//                map.put("remark", remark);
//                map.put("createdTime", createdTime);
//
//                list.add(map);

                resultSetMetaData = re.getMetaData();
                list.add(rowMap(resultSetMetaData, re));

            }
                return list;

        }catch (SQLException e){
            e.printStackTrace();
            return null;
            //throw new RewriteException(e);
        }finally {
            re.close();
            stat.close();
            conn.close();
        }
    }

    public Map<String,Object> rowMap(ResultSetMetaData resultSetMetaData, ResultSet rs) throws SQLException {
        Map<String,Object> map = new HashMap<>();

        //获取列的数量
        int columnCount = resultSetMetaData.getColumnCount();
        //此循环执行结束表示一行记录映射结束
        for(int i = 1; i <= columnCount; i++){
            //获取列别名,没有起别名就是列的名字
            String columnName = resultSetMetaData.getColumnLabel(i);
            //将列的名字作为key,列的值作为value存储到map集合
            map.put(columnName, rs.getObject(columnName));
        }
        return map;
    }

}






















